<template>
  <a-drawer
    :title="title"
    placement="right"
    :closable="true"
    :width="width"
    :visible="visible"
    @close="handleCancel"
    destroyOnClose
  >
    <a-spin :spinning="confirmLoading">
      <j-form-container>
        <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
          <a-row>
            <a-col :span="24">
              <a-form-model-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplier">
                <a-input v-model="supplierName"  placeholder="请输入供应商" disabled
                         style="width: 85%"/>
                <a-button type="primary" style="margin-left: 10px" @click="chooseSupplier">选择</a-button>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="材料类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialType">
                <a-input v-model="materialTypeName" placeholder="请输入材料类型" disabled style="width: 85%"/>
                <a-button type="primary" style="margin-left: 10px" @click="chooseMaterialType">选择</a-button>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="currentChoosePersonInCharge">
                <a-input v-model="currentChoosePersonInCharge" placeholder="请输入负责人" disabled style="width: 85%"/>
                <a-button type="primary" style="margin-left: 10px" @click="choosePersonInCharge">选择</a-button>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="材料编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialSerial">
                <a-input v-model="model.materialSerial" placeholder="请输入材料编号"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialName">
                <a-input v-model="model.materialName" placeholder="请输入名称"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="型号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="modelNumber">
                <a-input v-model="model.modelNumber" placeholder="请输入型号"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="规格" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="specifications">
                <a-input v-model="model.specifications" placeholder="请输入规格"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="品牌" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="brand">
                <a-input v-model="model.brand" placeholder="请输入品牌"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="unit">
                <a-input v-model="model.unit" placeholder="请输入单位"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="材料状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="status">
                <a-radio-group button-style="solid" v-model="model.status">
                  <a-radio-button :value="1">
                    启用
                  </a-radio-button>
                  <a-radio-button :value="2">
                    禁用
                  </a-radio-button>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="市场价" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="marketPrice">
                <a-input-number v-model="model.marketPrice" placeholder="请输入市场价" style="width: 100%"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="预算价" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="estimatedCost">
                <a-input-number v-model="model.estimatedCost" placeholder="请输入预算价" style="width: 100%"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="成本价" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="costPrice">
                <a-input-number v-model="model.costPrice" placeholder="请输入成本价" style="width: 100%"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="材料图片" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="progressId">
                <div class="clearfix">
                  <a-upload
                    :action="uploadAction"
                    :beforeUpload="doBeforeUpload"
                    list-type="picture-card"
                    :file-list="fileList"
                    :headers="headers"
                    :data="{'biz':'temp'}"
                    :returnUrl="returnUrl"
                    :transformFile="transformFile"
                    @preview="handlePreview"
                    @change="handleChange"
                  >
                    <div v-if="fileList.length < 8">
                      <a-icon type="plus"/>
                      <div class="ant-upload-text">
                        上传
                      </div>
                    </div>
                  </a-upload>
                  <a-modal :width="previewWidth" :visible="previewVisible" :footer="null" @cancel="handleClose">
                    <img alt="example" style="width: 100%" :src="previewImage"/>
                  </a-modal>
                </div>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>

        <choose-supplier-modal ref="chooseSupplierModal" @ok="chooseSupplierOk($event)"></choose-supplier-modal>
        <choose-material-type-modal ref="chooseMaterialTypeModal" @ok="chooseMaterialTypeOk($event)"></choose-material-type-modal>
        <choose-person-in-charge-modal ref="choosePersonInChargeModal" @selectFinished="choosePersonInChargeOk($event)"></choose-person-in-charge-modal>
      </j-form-container>
    </a-spin>
    <a-button type="primary" style="width: 100%" @click="handleOk">保存</a-button>
  </a-drawer>

  <!--<j-modal
    :title="title"
    :width="width"
    :visible="visible"
    switchFullscreen
    @ok="handleOk"
    :maskClosable="false"
    :okButtonProps="{ class:{'jee-hidden': disableSubmit} }"
    @cancel="handleCancel"
    cancelText="关闭">


  </j-modal>-->
</template>

<script>
  import { httpAction } from '@/api/manage'
  import * as imageConversion from 'image-conversion'
  import Vue from "vue";
  import {ACCESS_TOKEN} from "@/store/mutation-types"
  import {getFileAccessHttpUrl} from '@/api/manage'
  import chooseSupplierModal from './chooseSupplierModal'
  import chooseMaterialTypeModal from './chooseMaterialTypeModal'
  import choosePersonInChargeModal from './choosePersonInChargeModal'
  import {USER_INFO} from "../../../../../store/mutation-types";

  function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }

  export default {
    name: 'GhSupplychainMaterialModal',
    components: {
      chooseSupplierModal,chooseMaterialTypeModal,choosePersonInChargeModal
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        title:'',
        previewWidth: '70%',
        width: '100%',
        visible: false,
        disableSubmit: false,
        model: {},
        oldModel:{},
        supplierName: '',
        currentChooseSupplier:{},
        currentChooseMaterialType:{},
        currentChoosePersonInCharge:"",
        materialTypeName: "",
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        confirmLoading: false,
        validatorRules: {
          materialName:[
            { required: true, message: '名称不能为空' },
          ],
          materialSerial:[
            { required: true, message: '材料编号不能为空' },
          ],
          costPrice:[
            { required: true, message: '成本价不能为空' },
            {"pattern": /^([0-9][0-9]*)+(\.[0-9]{1,3})?$/,"message": "只能输入正数，小数点保留三位"},
          ],
        },
        url: {
          add: "/ghSupplychainMaterial/add",
          edit: "/ghSupplychainMaterial/edit",
          queryById: "/ghSupplychainMaterial/queryById"
        },
        fileList: [],
        newFileList: [],
        previewVisible: false,
        previewImage: '',
        uploadAction: window._CONFIG['domianURL'] + "/sys/oss/file/upload",
        headers: {},
        uploadGoOn:true,
        returnUrl: {
          type: Boolean,
          required: false,
          default: true
        },
      }
    },
    created() {
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token": token}
      //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      add() {
        let userInfo = Vue.ls.get(USER_INFO)
        let obj = {status:1};
        this.currentChoosePersonInCharge = userInfo.realname;
        this.model = Object.assign({}, obj);
        this.visible = true;
      },
      edit(record) {
        this.model = Object.assign({}, record);
        this.oldModel = Object.assign({}, record);
        if(record.ghSupplychainSupplier) {
          this.supplierName = record.ghSupplychainSupplier.supplierName;
        }

        this.materialTypeName = record.materialTypeName;
        this.currentChooseSupplier = record.ghSupplychainSupplier;
        this.currentChoosePersonInCharge = record.personInCharge;
        this.currentChooseMaterialType = record.ghSupplychainMaterialType;
        if (record.images){
          const images = [...record.images]
          for (let i=0;i<images.length;i++){
            if (images[i] != ""){
              let file = {
                index:i,
                key:(i+1),
                uid:(i+1),
                name: images[i],
                url:getFileAccessHttpUrl(images[i]),
                response:{
                  message: images[i],
                  result: images[i]
                }
              }
              this.fileList.push(file)
            }
          }
        }
        this.visible = true;
      },
      handleOk () {
        let that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            let httpurl = '';
            let method = '';
            if (!this.model.id) {
              httpurl += this.url.add;
              method = 'post';
            } else {
              httpurl += this.url.edit;
              method = 'put';
            }
            if (this.currentChooseSupplier == null || this.currentChooseSupplier.supplierName == null){
              this.$message.error("请选择供应商")
              return;
            } else {
              this.model.supplierId = this.currentChooseSupplier.id;
            }

            if (this.materialTypeName == null){
              this.$message.error("请选择材料的类型")
              return;
            } else {
              this.model.materialType = this.currentChooseMaterialType.id;
            }

            if (this.currentChoosePersonInCharge == null || this.currentChoosePersonInCharge == ""){
              this.$message.error("请选择材料负责人");
              return;
            } else {
              this.model.personInCharge = this.currentChoosePersonInCharge;
            }

            let images = "";
            if(this.fileList.length > 0) {
              for (let i = 0; i < this.fileList.length; i++) {
                images += this.fileList[i].response.message + ",";
              }
            }
            this.model.materialImage = images;
            let params = [];
            this.model.ghSupplychainSupplier = this.currentChooseSupplier;
            this.model.ghSupplychainMaterialType = this.currentChooseMaterialType;
            params.push(this.model);  //这是更新之后的数据
            if (this.model.id){
              params.push(this.oldModel); //这是更新前的数据
            }
            httpAction(httpurl, params, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close()
            })
          }
        })
      },
      handleCancel () {
        this.close()
      },
      transformFile(file) {
        return new Promise((resolve, reject) => {
          if (file.size > 5 * 1024 * 1024) {
            imageConversion.compress(file,0.8).then(res => {
              res = new File([res], file.name, {type: res.type, lastModified: Date.now()})
              resolve(res)
            })
          } else {
            resolve(file);
          }
        })
      },
      doBeforeUpload(file){
        let fileType = file.type;
        if (fileType.indexOf('image')<0){
          this.$message.warning('请上传图片');
          this.uploadGoOn=false
          return false;
        }
        const isLt100M = file.size / 1024 / 1024 < 100
        if (!isLt100M) {
          this.$message.error('上传文件大小不能超过 100MB!')
          this.uploadGoOn=false
          return false;
        }
        return true;
      },
      async handlePreview(file) {
        if (!file.response.result && !file.preview) {
          file.preview = await getBase64(file.originFileObj);
        }
        this.previewImage = file.response.result || file.preview;
        this.previewVisible = true;
      },
      handleChange(info) {
        if (!info.file.status && this.uploadGoOn === false) {
          info.fileList.pop();
        }
        let fileList = info.fileList
        if (info.file.status === 'done') {
          if (this.number > 0) {
            fileList = fileList.slice(-this.number);
          }
          if (info.file.response.success) {
            fileList = fileList.map((file) => {
              if (file.response) {
                // let reUrl = file.response.message;
                // file.url = getFileAccessHttpUrl(reUrl);
                file.url = file.response.result;
              }
              return file;
            });
          }
          //this.$message.success(`${info.file.name} 上传成功!`);
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败.`);
        } else if (info.file.status === 'removed') {
          this.handleDelete(info.file)
        }
        this.fileList = fileList
        if (info.file.status === 'done' || info.file.status === 'removed') {
          //returnUrl为true时仅返回文件路径
          if (this.returnUrl) {
            this.handlePathChange()
          } else {
            //returnUrl为false时返回文件名称、文件路径及文件大小
            this.newFileList = [];
            for (var a = 0; a < fileList.length; a++) {
              if (fileList[a].status === 'done') {
                var fileJson = {
                  fileName: fileList[a].name,
                  filePath: fileList[a].response.message,
                  fileSize: fileList[a].size
                };
                this.newFileList.push(fileJson);
              } else {
                return;
              }
            }
            this.$emit('change', this.newFileList);
          }
        }
      },
      //关闭预览照片
      handleClose() {
        this.previewVisible = false;
      },
      handlePathChange() {
        let uploadFiles = this.fileList
        let path = ''
        if (!uploadFiles || uploadFiles.length == 0) {
          path = ''
        }
        let arr = [];
        if (!this.isMultiple && uploadFiles.length > 0) {
          arr.push(uploadFiles[uploadFiles.length - 1].response.message)
        } else {
          for (let a = 0; a < uploadFiles.length; a++) {
            if (uploadFiles[a].status === 'done') {
              arr.push(uploadFiles[a].response.message)
            } else {
              return;
            }
          }
        }
        if (arr.length > 0) {
          path = arr.join(",")
        }
        this.$emit('change', path);
      },
      //删除图片
      handleDelete(file){
        const item = this.fileList.find(item => item.url == file.url);
        delete this.fileList[item.index];
      },
      //选择供应商
      chooseSupplier() {
        //add
        this.$refs.chooseSupplierModal.visible = true
        this.$refs.chooseSupplierModal.title = "请选择供应商";
      },
      chooseSupplierOk(obj) {
        this.currentChooseSupplier = {};
        this.currentChooseSupplier = obj;
        this.supplierName = obj.supplierName;
      },
      //选择材料类型
      chooseMaterialType(){
        this.$refs.chooseMaterialTypeModal.visible = true
        this.$refs.chooseMaterialTypeModal.title = "请选择材料类型";
      },
      chooseMaterialTypeOk(obj){
        this.currentChooseMaterialType = {};
        this.materialTypeName = obj.materialTypeName;
        this.currentChooseMaterialType = obj;
      },
      //选择负责人
      choosePersonInCharge(){
        this.$refs.choosePersonInChargeModal.visible = true
        this.$refs.choosePersonInChargeModal.title = "请选择材料负责人";
      },
      choosePersonInChargeOk(obj){
        this.currentChoosePersonInCharge = "";
        this.currentChoosePersonInCharge = obj.realname;
      },
      close () {
        this.visible = false;
        this.currentChooseSupplier = {};
        this.currentChooseMaterialType = {};
        this.currentChoosePersonInCharge = "";
        this.materialTypeName = "";
        this.model = {};
        this.fileList = [];
        this.supplierName = '';
      },
    }
  }
</script>